<template>
  <div class="container">
    <el-card>
      <div class="clearfix" slot="header">试题录入</div>
      <el-form :model="qnform" :rules="rules" ref="form" label-width="120px">
        <!-- 学科 -->
        <el-form-item label="学科: " prop="subjectID">
          <el-select
            @change="changeSubject"
            v-model="qnform.subjectID"
            placeholder="请选择学科"
            style="width:400px"
          >
            <el-option
              v-for="item in subjectOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 目录 -->
        <el-form-item label="目录:" prop="catalogID">
          <el-select v-model="qnform.catalogID" placeholder="请选择目录" style="width:400px">
            <el-option
              v-for="item in catalogOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 企业 -->
        <el-form-item label="企业:" prop="enterpriseID">
          <el-select v-model="qnform.enterpriseID" placeholder="请选择企业" style="width:400px">
            <el-option
              v-for="item in enterpriseOptions"
              :key="item.id"
              :label="item.company"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 城市 （市，地区）选择器  级联（选项与选项之间有从属关系）-->
        <el-form-item label="城市:" prop="city">
          <el-select
            v-model="qnform.province"
            placeholder="请选择省份"
            @change="getAreaOptions"
            style="width:198px"
          >
            <el-option v-for="item in cityOptions" :key="item" :label="item" :value="item"></el-option>
          </el-select>
          <el-select v-model="qnform.city" placeholder="请选择城市" style="width:198px;margin-left:4px">
            <el-option v-for="item in areaOptions" :key="item" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <!-- 方向 -->
        <el-form-item label="方向:" prop="direction">
          <el-select v-model="qnform.direction" placeholder="请选择方向">
            <el-option v-for="item in directionOptions" :key="item" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <!-- 题型--单选框 -->
        <el-form-item label="题型:" prop="questionType">
          <el-radio-group v-model="qnform.questionType">
            <el-radio
              v-for="item in questionType"
              :key="item.value"
              :label="item.value+''"
            >{{item.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 难度-单选框 -->
        <el-form-item label="难度:" prop="difficulty">
          <el-radio-group v-model="qnform.difficulty">
            <el-radio
              v-for="item in difficulty"
              :key="item.value"
              :label="item.value+''"
            >{{item.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 题干-富文本 -->
        <el-form-item label="题干:" prop="question">
          <quill-editor
            type="textarea"
            @blur="checkQustion"
            v-model="qnform.question"
            :autosize="{minRows: 2, maxRows: 6}"
            :options="editorOptions"
          ></quill-editor>
        </el-form-item>
        <!-- 选项 跟题目的难易程度关联，简单复杂一样，简答需要换成文本-->
        <el-form-item label="选项：" prop="options" v-if="qnform.questionType!== '3'">
          <div v-if="qnform.questionType === '1'">
            <el-radio-group v-model="qnform.people" @change="apple">
              <div v-for="item in qnform.options" :key="item.code">
                <el-radio :label="item.code">{{item.code}}</el-radio>
                <el-input v-model="item.title" placeholder="请输入选项" style="width:240px" />
              </div>
            </el-radio-group>

            <!-- 添加按钮 -->
            <!-- <el-button disabled type="danger" @click="addOption" size="small">+增加选项与答案</el-button> -->
          </div>
          <div v-if="qnform.questionType === '2'">
            <div v-for="item in qnform.options" :key="item.code">
              <el-checkbox :label="item.code">{{item.code}}</el-checkbox>
              <el-input v-model="item.title" placeholder="请输入选项" style="width:240px" />
              <!-- <el-upload
                :show-file-list="false"
                :on-success="handleUploadSuccess"
                :before-upload="beforeUpload"
                :action="uploadUrl"
              >
                <el-button size="small" type="primary">上传图片</el-button>
              </el-upload>-->
            </div>
            <!-- 添加按钮 -->
            <el-button type="danger" @click="addOption" size="small">+增加选项与答案</el-button>
          </div>
        </el-form-item>
        <!-- 视频解析 输入框-->
        <el-form-item label="解析视频:">
          <el-input
            type="text"
            v-model="qnform.videoURL"
            style="width:400px"
            :autosize="{minRows: 2, maxRows: 6}"
          ></el-input>
        </el-form-item>
        <!-- 答案解析 富文本-->
        <el-form-item label="答案解析:" prop="question">
          <quill-editor
            type="textarea"
            v-model="qnform.answer"
            :autosize="{minRows: 2, maxRows: 6}"
          ></quill-editor>
        </el-form-item>
        <!-- 题目备注 文本域-->
        <el-form-item label="题目备注">
          <el-input
            type="textarea"
            v-model="qnform.remarks"
            :autosize="{minRows: 4, maxRows: 6}"
            style="width:400px"
          ></el-input>
        </el-form-item>
        <!-- 试题标签 输入框-->
        <el-form-item label="试题标签:" prop="tags">
          <el-select
            v-model="qnform.tags"
            placeholder="请选择标签"
            multiple
            filterable
            allow-create
            default-first-option
            style="width:400px"
          >
            <el-option v-for="i in tagsOptions" :key="i.value" :label="i.label" :value="i.label"></el-option>
          </el-select>
        </el-form-item>
        <!-- 提交按钮 -->
        <el-form-item>
          <el-button v-if="!($route.query.id)" type="primary" @click="submitForm()">提交</el-button>
          <el-button v-else @click="update()" type="success">确认修改</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>
<script>
// 获取学科列表
import { simple as getSubjectOptions } from '@/api/hmmm/subjects'
// 获取目录列表
import { simple as getCatalogOptions } from '@/api/hmmm/directorys'
// 获取企业
import { list as getCompanyOptions } from '@/api/hmmm/companys'
// 获取省份-城市
import { provinces as getCityOptions, citys as getAreaOptions } from '@/api/hmmm/citys'
// 获取方向+题型
import { direction, questionType, difficulty } from '@/api/hmmm/constants'
// 获取标签
import { simple as getTagOptions } from '@/api/hmmm/tags'
// 获取基础题库 添加 修改
import { detail, add, update } from '@/api/hmmm/questions'
// 富文本
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'
import hljs from 'highlight.js'
import 'highlight.js/styles/vs2015.css'
// 上传图片
import { getToken } from '@/utils/auth'
export default {
  components: {
    quillEditor
  },
  data () {
    return {
      token: getToken(),
      // 富文本 ：使用高亮插件；安装高亮插件，导入转换文本插件，输入时显示高亮
      editorOptions: {
        placeholder: '',
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'],
            [{ list: 'ordered' }, { list: 'bullet' }],
            ['blockquote'],
            ['code-block', 'image', 'link']
          ],
          // 语法高亮
          syntax: {
            highlight: text => hljs.highlightAuto(text).value
          }
        }
      },
      // 试题对象
      qnform: {
        // 学科
        subject: '',
        // 目录
        catalog: '',
        // 企业
        company: '',
        // 选择省份
        province: '',
        // 选择城市
        city: '',
        //  选择方向
        direction: '',
        // 选择题型
        questionType: '1',
        // 选择难度
        difficulty: '1',
        // 请输入题干
        question: '',
        // 选项
        options: [
          { isRight: false, code: 'A', title: '', img: '' },
          { isRight: false, code: 'B', title: '', img: '' },
          { isRight: false, code: 'C', title: '', img: '' },
          { isRight: false, code: 'D', title: '', img: '' }
        ],
        people: ''
        // 视频解析
        // analysis: '',
        // 答案解析
        // videoUrl: '',
        // 题目备注
        // answerAnalysis: '',
        // 试题标签
        // remarks: ''
      },
      // 校验规则
      rules: {
        subjectID: [
          { required: true, message: '请选择学科', trigger: 'change' }
        ],
        catalogID: [
          { required: true, message: '请选择目录', trigger: 'change' }
        ],
        enterpriseID: [
          { required: true, message: '请选择企业', trigger: 'change' }
        ],
        province: [
          { required: true, message: '请选择省份', trigger: 'change' }
        ],
        city: [
          { required: true, message: '请选择城市', trigger: 'change' }
        ],
        direction: [
          { required: true, message: '请选择方向', trigger: 'change' }
        ],
        questionType: [
          { required: true, message: '请选择题型', trigger: 'change' }
        ],
        difficulty: [
          { required: true, message: '请选择难度', trigger: 'change' }
        ],
        question: [
          { required: true, message: '请输入题干', trigger: 'blur' }
        ]
      },
      // 学科选项
      subjectOptions: [],
      // 目录选项
      catalogOptions: [],
      // 企业选项
      enterpriseOptions: [],
      // 城市-地区 选择
      areaOptions: getAreaOptions(),
      cityOptions: getCityOptions(),
      // 方向
      directionOptions: direction,
      // 题型
      questionType: questionType,
      // 难度
      difficulty: difficulty,
      // 标签选项
      tagsOptions: []
    }
  },
  created () {
    // 获取学科列表
    this.getSubjectOptions()
    // 获取企业列表
    this.getCompanyOptions()
    // 获取标签列表
    this.getTagOptions()
    if (this.$route.query.id) {
      this.getQuestion()
    }
  },
  watch: {
    '$route.query': function () {
      if (this.$route.query.id) {
        this.getQuestion()
      } else {
        this.qnform = {
          // 学科
          subject: '',
          // 目录
          catalog: '',
          // 企业
          company: '',
          // 选择省份
          province: '',
          // 选择城市
          city: '',
          //  选择方向
          direction: '',
          // 选择题型
          questionType: '1',
          // 选择难度
          difficulty: '1',
          // 请输入题干
          question: '',
          // 选项
          options: [
            { isRight: false, code: 'A', title: '', img: '' },
            { isRight: false, code: 'B', title: '', img: '' },
            { isRight: false, code: 'C', title: '', img: '' },
            { isRight: false, code: 'D', title: '', img: '' }
          ]
        }
        this.$nextTick(() => {
          this.$refs.form.clearValidate()
        })
      }
    }
  },
  methods: {
    // 获取题目信息
    async getQuestion () {
      const data = await detail({ id: this.$route.query.id })
      data.tags = data.tags.split(',')
      data.options = data.options.map(i => {
        i.isRight = i.isRight === 1
        return i
      })
      this.qnform = data
      // 目录
      const res = await getCatalogOptions({ subjectID: this.qnform.subjectID })
      console.log(res)
      this.catalogOptions = res
      const res1 = await getTagOptions({ subjectID: this.qnform.subjectID })
      this.tagsOptions = res1.data
      // 滚动到顶部
      await this.$nextTick(() => {
        window.scrollTo(0, 0)
      })
    },
    // 获取学科列表
    async getSubjectOptions () {
      const { data } = await getSubjectOptions()
      this.subjectOptions = data
      // console.log(data)
    },
    // 修改学科
    async changeSubject (subjectID) {
      this.qnform.catalog = null
      const { data } = await getCatalogOptions({ subjectID: this.qnform.subjectID })
      this.catalogOptions = data
      this.qnform.tags = null
      // const data1= await
    },

    // 获取目录
    // async getCatalogOptions () {
    //   const { data } = await getCatalogOptions()
    //   this.CatalogOptions = data
    // },
    // 获取企业
    async getCompanyOptions () {
      const { data } = await getCompanyOptions()
      this.enterpriseOptions = data.items
      // console.log(data)
    },
    // 获取城市
    async getAreaOptions (cityName) {
      // 清空  地区选中的值
      this.qnform.city = null
      // cityName 是你选中城市后的值
      this.areaOptions = await getAreaOptions(cityName)
    },
    // 选项---添加按钮
    addOption () {
      this.qnform.options.push({
        isRight: false,
        code: String.fromCharCode(65 + this.qnform.options.length),
        title: '',
        img: ''
      })
    },
    // 获取标签
    async getTagOptions () {
      const { data } = await getTagOptions()
      this.tagsOptions = data
      console.log(data)
    },
    // 校验题干
    checkQustion () {
      // 调用el-form组件的 validateField 校验  question  字段
      this.$refs.form.validateField('question')
    },
    // 提交按钮
    submitForm () {
      this.$refs.form.validate(async valid => {
        console.log(111111111111)
        console.log(valid)
        if (valid) {
          const data = { ...this.qnform }
          data.tags = data.tags.join(',')
          await add(data)
          this.$message.success('添加成功')
          this.$router.push('/questions/list')
        }
      })
    },
    apple () {
      console.log(this.qnform.people)
      this.qnform.options.isRight = true
    },
    update () {
      this.$refs.form.validate(async valid => {
        if (valid) {
          const data = { ...this.qsForm }
          data.tags = data.tags.join(',')
          await update(data)
          this.$message.success('修改成功')
          this.$router.push('/questions/list')
        }
      })
    }

  }
}

</script>
<style  scoped>
.container {
  padding: 0 20px;
}
</style>
